package megrez.bussiness.schedule.component;

import java.util.List;

import org.springframework.stereotype.Component;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import megrez.bussiness.schedule.entity.Job;
import megrez.bussiness.schedule.entity.Job.State;
import megrez.bussiness.schedule.repository.JobRepository;

/**
 * 定时任务服务
 *  
 * @author Lucky Yang
 * @since 0.0.1
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ScheduleManagerComponent {
    private final CronTaskRegistrar cronTaskRegistrar;
    private final JobRepository jobRepository;

    public void start(Job job) {
        if (!State.STOPPED.equals(job.getState())) {
            return;
        }
        cronTaskRegistrar.addTask(job);
    }

    public void startAll() {
        cronTaskRegistrar.destroy();

        // 默认开启的任务
        List<Job> jobList = jobRepository.findByEnabled(true);
        for (Job job : jobList) {
            start(job);
        }

        log.info("定时任务已加载完毕, 总共 {} 个", jobList.size());        
    }

    public void shutdown(Job job) {
        if (State.STOPPED.equals(job.getState())) {
            return;
        }

        cronTaskRegistrar.removeCronTask(job.getId());
    }

    public void shutdownAll() {
        cronTaskRegistrar.destroy();
        log.info("所有的定时任务都已关闭");        
    }
}
